#include <iostream>
#include <typeinfo>
#include <string>

class Any
{
private:
    class Holder
    {
    public:
        Holder() {}
        virtual const std::type_info& Type() = 0;
        virtual Holder *Clone() = 0;
        ~Holder() {}
    };
    template<class T>
    class PlaceHolder : public Holder
    {
    public:
        PlaceHolder(T val) :m_val(val) {}
        const std::type_info& Type()
        {
            return typeid(T);
        }
        // ????
        Holder* Clone()
        {
            return new PlaceHolder(m_val);
        }
        ~PlaceHolder() {}
    public:
        T m_val;
    };
    Holder *m_content;
public:
    Any() :m_content(nullptr) {}
    template<class T>
    Any(const T& val) :m_content(new PlaceHolder<T>(val)) {}
    Any(const Any& other) :m_content(other.m_content->Clone()) {}
    ~Any() { delete m_content; }
    Any& Swap(Any& other)
    {
        std::swap(m_content, other.m_content);
        return *this;
    }
    template<class T>
    // 获取内容
    T* Get() 
    {
        if (typeid(T) != m_content->Type())
            return nullptr;
        return &dynamic_cast<PlaceHolder<T>*>(m_content)->m_val;
    }
    template<class T>
    Any& operator=(const T& val) 
    {
        Any(val).Swap(*this);
        return *this;
    }
    Any& operator=(const Any& other) 
    {
        m_content = other.m_content->Clone();
        return *this;
    }
};

int main()
{
    Any a;
    a = 10;
    int *pa = a.Get<int>();
    std::cout << *pa << std::endl;
    a = std::string("nihao");
    std::string* s = a.Get<std::string>();
    std::cout << *s << std::endl;
    return 0;
}